package com.codeczx.servicedemo;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.IntDef;
import android.util.Log;

import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

public class MyService extends Service {

    boolean isDownloading;
    LinkedBlockingQueue<Integer> queue = new LinkedBlockingQueue<>();

    public MyService() {
    }

    @Override
    public int onStartCommand(Intent intent, int flags, final int startId) {
        final int count = intent.getExtras().getInt(MainActivity.COUNT);
        Log.i("codeczx","onStartCommand:"+count);
        if(!isDownloading){
            isDownloading = true;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    startDownload(count);
                }
            }).start();
        }else{
            queue.add(count);
        }

        return START_NOT_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    public void startDownload(int id){
        int i = 0;
        while(i<10){
            Log.i("codeczx","misson"+id+" downloading..."+i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            i++;
        }
        if(queue.size()!=0){
            startDownload(queue.poll());
        }else{
            stopSelf();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("codeczx","onDestroy");
    }
}
